﻿using System;
using System.Linq;
using System.Web;
using Dosimetria.Models;
using System.Web.Mvc;
using Dosimetria.DAL;


namespace Dosimetria.Authorization
{
    public class RequiresAuthorization : AuthorizeAttribute
    {
        private Querys db = new Querys();

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
                throw new ArgumentNullException("AuthorizeFilterAttribute");

            var result = db.getFuncionalidadesByNombreUsuario(HttpContext.Current.User.Identity.Name);

            string actionName = filterContext.ActionDescriptor.ActionName;
            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

            if (result.Count() == 0 || result.FirstOrDefault(f => f.accion == actionName && f.controlador == controllerName) == null)
                if (filterContext.HttpContext.Request.IsAuthenticated)
                    filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult(403);
                else
                    filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}